package com.qfedu.knowledge.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfedu.knowledge.entity.constant.ElasticSearchConsant;
import com.qfedu.knowledge.entity.dto.BasePageDTO;
import com.qfedu.knowledge.entity.enums.HighLightColumnEnum;
import com.qfedu.knowledge.entity.vo.ElasticSearchPageVO;
import com.qfedu.knowledge.entity.vo.QuestionInfoVO;
import com.qfedu.knowledge.service.ElasticSearchService;
import com.qfedu.knowledge.strategy.StrategyContext;
import com.qfedu.knowledge.util.ElasticSearchUtils;
import lombok.SneakyThrows;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName ElasticSearchServiceImpl
 * @Author ykx
 * @Date 2024/5/22 23:23
 * @Version 1.0
 */
@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ElasticSearchUtils elasticSearchUtils;

    @Override
    @SneakyThrows
    public ElasticSearchPageVO getQuestionFromES(BasePageDTO basePageDTO, String keyword) {
        // 根据题目查询关键词，并获得总记录数
        ElasticSearchPageVO elasticSearchPageVO = new ElasticSearchPageVO();
        SearchResponse response = elasticSearchUtils.highLightQuery(ElasticSearchConsant.HIGH_LIGHT_COLUMNS, keyword, basePageDTO);
        elasticSearchPageVO.setTotal(response.getHits().getTotalHits());

        // 封装数据
        List<QuestionInfoVO> questionInfoVOS = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            QuestionInfoVO questionInfoVO = objectMapper.readValue(hit.getSourceAsString(), QuestionInfoVO.class);

            // 获取高亮的数据
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            for (String column : highlightFields.keySet()) {
                HighLightColumnEnum lightColumnEnum = HighLightColumnEnum.getEnumByColumn(column);
                StrategyContext strategyContext = new StrategyContext(lightColumnEnum);
                if (Objects.nonNull(lightColumnEnum) && Objects.nonNull(highlightFields.get(column))) {
                    strategyContext.contextMethod(questionInfoVO, highlightFields.get(column));
                }
            }
            questionInfoVOS.add(questionInfoVO);
        }
        elasticSearchPageVO.setRecords(questionInfoVOS);
        return elasticSearchPageVO;
    }
}
